package com.cloud.jucTest;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class CasTest implements Runnable{
    long start = System.currentTimeMillis();
    int i = 0;
    @Override
    public void run() {
        int j = i;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            Unsafe unsafe = (Unsafe) f.get(null);
            long offset = unsafe.objectFieldOffset(CasTest.class.getDeclaredField("i"));
            while (!unsafe.compareAndSwapInt(this, offset, j, j + 1)) {
                j = i;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("the business is done has use: " + (System.currentTimeMillis() - start));
    }

    public static void main(String[] args) throws InterruptedException {
        CasTest test = new CasTest();
        new Thread(test).start();
        new Thread(test).start();
        Thread.sleep(1000);
        System.out.println("the finally result is " + test.i);
    }
}
